<?php
require_once('lib/ftree_utils.php');
include('lib/adodb-time.inc.php');
require_once "HTML/Template/IT.php";
$debug=false;


function writeParent($id, $var)
{
	global $tpl;

	$query = "SELECT * FROM `person` WHERE `id` = $id";
	$result = mysql_query($query) or die("Query failed : " . mysql_error());
	$data = mysql_fetch_array($result, MYSQL_ASSOC);
	
	$full = formatName($data['first'], $data['middle'], $data['last'], $data['suffix'], $data['nick'], "fmls");
	$dates = combineDates($data['dob'],$data['dod']);
	$tpl->setVariable($var, $full);
	$tpl->setVariable("${var}ID", $data['id']);
	$tpl->setVariable("${var}Dates", $dates);
	
	mysql_free_result($result);
}

function writeGParent($id, $fLabel, $mLabel)
{
	global $tpl;

	$query = "SELECT * FROM `person` WHERE `id` = $id";
	$result = mysql_query($query) or die("Query failed : " . mysql_error());
	$data = mysql_fetch_array($result, MYSQL_ASSOC);
	$fid = $data['father'];
	$mid = $data['mother'];
	mysql_free_result($result);

	if ($fid != "") { writeParent($fid, $fLabel); }
	if ($mid != "") { writeParent($mid, $mLabel); }
}

function writeKids($fID, $mID, $var)
{
	global $tpl;

        $query = "SELECT * FROM `person` WHERE `father` = $fID AND `mother` = $mID ORDER BY `dob` ASC";
        $result = mysql_query($query) or die("Query failed : " . mysql_error());

        while ($data = mysql_fetch_array($result, MYSQL_ASSOC)) {

                $full =  formatName($data['first'], $data['middle'], $data['last'], $data['suffix'], $data['nick'], "fm");
		$dates = combineDates($data['dob'],$data['dod']);
		$tpl->setCurrentBlock($var) ;
		$tpl->setVariable($var, $full) ;
		$tpl->setVariable("${var}Dates", $dates) ;
		$tpl->setVariable("${var}ID", $data['id']) ;
		$tpl->parseCurrentBlock($var);

        }
        mysql_free_result($result);
}

function combineDates($dob, $dod)
{
	$dob = formatDate($dob,"short");
	$dod = formatDate($dod,"short");
	$dates = "";
	if ($dob != "") {
		$dates = "$dob-";
	}
	if ($dod != "") {
		if ($dob == "") {
			$dates = "-";
		}
		$dates .= "$dod";
	}
	return $dates;
}

function paraEncode($text)
{
	global $mode;

	if ($mode == "r") {
		$text = str_replace("\n","<br>",$text);
	}
	return $text;
}


// MAIN

// CONNECT TO DB

$link = mysql_connect("localhost", "ftreeweb", "ftree_web")
   or die("Could not connect : " . mysql_error());
mysql_select_db("ftree") or die("Could not select database");

// GET HTTP "GET" VARS

if ( isset($_GET['id']) ) {
        $id = $_GET['id'];
} else {                        
	$loginid = $_SERVER['REMOTE_USER'];
	$query = "SELECT * FROM `logins` WHERE `userid` = '$loginid'";
	$result = mysql_query($query) or die("Query failed : " . mysql_error());
        $data = mysql_fetch_array($result, MYSQL_ASSOC);
	$id = $data['treeid'];          
	if ($id == "") { $id = 3054; }  # when in doubt, go to my card
	mysql_free_result($result);
}
$debug && print("Early ID=$id\n");
$id=preg_replace("/[^0-9]/","",$id);  //get rid of anything but numbers
if ($id < 1 || $id > pow(2,17)) {
	die("ID is out of range.");
}

// SET UP TEMPLATE

$isMobile = ChkIsMobile();
$tpl = new HTML_Template_IT("templates");
$isMobile ? $template = "tree_mtmpl2.html" : $template = "tree_tmpl2.html";

$status = $tpl->loadTemplatefile($template, true, true);


// GET PERSON

$query = "SELECT * FROM person WHERE `id` = $id";
$result = mysql_query($query) or die("Query failed : " . mysql_error());
$idData = mysql_fetch_array($result, MYSQL_ASSOC);

$full = formatName($idData['first'], $idData['middle'], $idData['last'], $idData['suffix'], $idData['nick'], "fmls");
$sex      = $idData['sex'   ];
$fatherID = $idData['father'];
$motherID = $idData['mother'];

/*$tpl->setVariable("PersonID", $idData['id']);
$tpl->setVariable("FullName", $full);
$dates = combineDates($idData['dob'],$idData['dod']);
$tpl->setVariable("PersonDates", $dates);
*/
mysql_free_result($result);
$debug && print("Full name is $full <br />");
$debug && print("ID after person=$id\n");

// GET PARENTS

writeParent($fatherID, "Father");
writeParent($motherID, "Mother");
$debug && print("ID after parents=$id\n");

// GET GRANDPARENTS

writeGParent($fatherID, "PGF", "PGM");
writeGParent($motherID, "MGF", "MGM");
$debug && print("ID after gparents=$id\n");

// GET SPOUSE(S)

if ( $sex == "M" ) {
	$query = "SELECT * FROM `marriage` WHERE `husband` = $id ORDER BY `date` ASC";
	$fID = $id;
} else {
	$query = "SELECT * FROM `marriage` WHERE `wife`    = $id ORDER BY `date` ASC";
	$mID = $id;
}

$spResult = mysql_query($query) or die("Query failed : " . mysql_error());
$debug && print("ID pre spouse while=$id\n");

$cntSpouses = 0;
while ($spData = mysql_fetch_array($spResult, MYSQL_ASSOC)) {
$debug && print("In spouse loop\n");
	if ( $sex == "M" ) {
		$spID = $spData['wife'];
		$mID  = $spID;
	} else {
		$spID = $spData['husband'];
		$fID  = $spID;
	}

	$query = "SELECT * FROM `person` WHERE `id` = $spID";
	$result = mysql_query($query) or die("Query failed : " . mysql_error());
	$persData = mysql_fetch_array($result, MYSQL_ASSOC);

	$spFull = formatName($persData['first'], $persData['middle'], $persData['last'], $persData['suffix'], $persData['nick'], "fmls");
	$spDates = combineDates($persData['dob'],$persData['dod']);
	$dom = formatDate($spData['date'],"short");
	if ($dom != "") {
		$dom = " (m. $dom)";
	}
	$cntSpouses++;
$debug && print("ID post spouse while=$id\n");

	mysql_free_result($result);

$debug && print("ID after spouse=$id\n");
// GET CHILDREN

	writeKids($fID, $mID, "Child");

// WRITE OUTER SPOUSE BLOCK
$debug && print("ID=$id\n");
	$tpl->setCurrentBlock("Spouses") ;
	$tpl->setVariable("PersonID", $id) ;
	$tpl->setVariable("FullName", $full);  // If not set here, won't display name
	$tpl->setVariable("Spouse", $spFull) ;
	$tpl->setVariable("SpouseID", $spID) ;
	$tpl->setVariable("MarriageID", $spData['id']) ;
	$tpl->setVariable("SpouseDates", $spDates);
	$tpl->setVariable("DOM", $dom);
	$tpl->parseCurrentBlock("Spouses") ;


} // END SPOUSE LOOP
$debug && print("Out of spouse loop\n");
$debug && print("Processed $cntSpouses spouses. <BR />");

// If the Spouses block is never defined once, FullName gets lost and the current
// person's name is not displayed.
If ( $cntSpouses == 0 ) {
$debug && print("Got no spouses for $id!\n");
	$tpl->setCurrentBlock("Spouses") ;
	$tpl->setVariable("PersonID", $id) ;
	$tpl->setVariable("FullName", $full);
	$tpl->setVariable("Spouse", "") ;
	$tpl->setVariable("SpouseID", "") ;
	$tpl->setVariable("MarriageID", "") ;
	$tpl->setVariable("SpouseDates", "");
	$tpl->setVariable("DOM", "");
	$tpl->parseCurrentBlock("Spouses") ;
}

//echo "</ol>\n\n";

if ( $sex == "M" ) {
	$fID = $id;
	$mID = 0;
} else {
	$fID = 0;
	$mID = $id;
}

writeKids($fID, $mID, "OthChild");

mysql_free_result($spResult);


// DONE -- CLEAN UP

mysql_close($link);

$debug && print("At end, ID=" . $idData['id'] . ", (or $id), name is $full. Re-setting...<br />");
$tpl->setVariable("PersonID", $idData['id']);  //somehow it's getting lost
$tpl->setVariable("FullName", $full);
$tpl->show();

?>
